<?php
namespace Home\Controller;

use Api\Event\CacheEvent;

/**
*游戏列表控制器
*@author susy<susy.liang@ilongyuan.com.cn>
*重写 liubo 2016-08-05
*/
class GameController extends HomeController {

    protected function _initialize(){
        parent::_initialize();
        C('DEFAULT_THEME', 'v4');
    }

	/**
	*首页列表
    *获取游戏列表数据
	*/
    public function index(){
        $id = I('id', 0, 'intval');
        if (!$id) {
            $this->redirect('/');
        }

        // 游戏视频
        $total = 0;
        $videos = $this->_videos($id, $total);
        if (IS_AJAX) {
            $this->ajaxReturn(['state'=>0, 'info'=>'操作成功', 'data'=>$videos, 'total' => $total]);
        }

        // 游戏基本数据
        $game = event('Game')->info($id);
        uri_format($game['logo']);
        uri_format($game['pc_background']);
        $game['is_scribe'] = event('GameScribe')->is_scribe(UID, $id);

        // 游戏关注排名写缓存
        $Redis = CacheEvent::instance(0);
        $gkey = 'IMBA.CACHE.WEB.EXPLORE.GAMES';
        $games = $Redis->get($gkey);
        if (empty($games)) {
            $games = event('Game')->getGamesSortByScribe();
            $Redis->setEx($gkey, 600, json_encode($games));
        } else {
            $games = json_decode($games, true);
        }
        foreach ($games as $key => $value) {
            if ($value['game_id'] == $id) {
                $game['rank'] = intval($key) + 1;
            }
        }

        // 游戏活跃用户写缓存
        $ukey = "IMBA.CACHE.WEB.EXPLORE.GAME_USER.{$id}";
        $users = $Redis->get($ukey);
        if (empty($users)) {
            $map = [
                'game_id' => $id,
                'type'    => 0,
                'status'  => 1,
                'race_id' => ['$eq' => null],
                'uid'     => ['$nin' => array_map('intval', C('EXCLUDE_USER_IDS', null, []))],
            ];
            $users = event('Video')->getTopUsers($map, 7, true);
            $Redis->setEx($ukey, 600, json_encode($users));
        } else {
            $users = json_decode($users, true);
        }
        unset($Redis);

        // 近日比赛
        $races = $this->_races($id);
        // 游戏资讯
        $newslist = event('news')->lists(['game_id' => $id], 1, 2);

        $this->assign([
            'game'     => $game,
            'users'    => $users,
            'videos'   => $videos,
            'total'    => $total,
            'races'    => $races,
            'newslist' => $newslist,
        ]);
        $this->title = $game['name'];
        setRedirect();
		$this->display();
    }

    private function _videos($game_id, &$total)
    {
        $p     = I('p', 1, 'intval');
        $this->pager = I('pager', 12, 'intval');
        $sort  = I('sort', '', 'trim');

        $map = [
            'game_id' => $game_id,
            'type'    => 0,
            'race_id' => ['$eq' => null],
        ];

        if ($sort == 'hot') {
            $order = 'play desc, create_time desc';
        } else {
            $order = 'create_time desc';
        }
        $videos = event('Video')->getBaseInfoLists($map, true, '', $p, $this->pager, $order);
        foreach ($videos as &$value) {
            $value['statis']['play'] = $value['play'];  
        }
        $total = event('Video')->total($map);
        return $videos;
    }

    private function _races($game_id = 0)
    {
        $rgEvent = event('RaceGroup');
        $curDate = date('Y-m-d H:i', time());
        $map = [
            'game_id' => $game_id,
            'state' => 1,
            'race_time' => ['lt', $curDate]
        ];
        $ids = $rgEvent->lists($map, 'id', 2, 0, 'race_time desc');
        return $this->_format_races($ids, false);
    }

   /**
    *获取游戏列表页数据
    *@return string 列表页的html
    */
    private function getList($id=0, $timestamp=0){

        $field  = 'id,name,cover,detail,scribe,create_time';

        if($id){
            $query = array('id'=>$id);
            $games = $this->gEvent->lists($query, $field);

        }else{

            $games = $this->gEvent->getGames(C('VIDOE_LIST_ROWS'), $timestamp, $field );
        }

        $gsEvent = A('Api/GameScribe', 'Event');
        
        foreach ($games as $key => &$game) {
            uri_format($game['cover']);
            UID && $game['isScribe'] = $gsEvent->is_scribe(UID, $game['id'])?1:0;
            $game['scribe'] = intval($game['scribe']);
            $data[] = $game;
        }
        
        $count = count($data);
        $this->timestamp = $data[$count-1]['create_time'];

        $this->data = $data;

        $strhtml = $this->fetch('Template:game');

        return $strhtml;
    }

    /**
    *ajax加载的游戏列表
    */
    public function ajaxList(){

        $id = I('id', 0, 'intval');
        $timestamp = I('timestamp', '', 'strip_tags');

        if(empty($timestamp))
            $this->ajaxReturn(array('state'=>-1, 'info'=>'参数有误'));
            
        $strhtml = $this->getList($id, $timestamp);

        $this->ajaxReturn(array('state'=>0, 'info'=>'操作成功', 'data'=>array('content'=>$strhtml)));

    }


    /** 
     * 获取游戏下视频信息
     * @author Legend. <xcx_legender@qq.com>
     * @param 
     * @return 
     */
    
    public function videos()
    {
        $this->id = $id = I('id', 0, 'intval');
        if (!$id)
        {
            $this->redirect('index');
        }
        $gEvent = A('Api/Game', 'Event');
        $game = $gEvent->info($id);
        if (!$game)
        {
            $this->redirect('index');
        }

        $vEvent = A('Api/Video', 'Event');

        $map = array();
        $map['game_id'] = $id;
        //$map['race_id'] = array('egt', null);//非比赛视频 
        $timestamp = I('timestamp', 0, 'intval');
        if($timestamp)
            $map['create_time'] =  array('lt', $timestamp);
        $listRow =  C('VIDOE_LIST_ROWS');
        $vids = $vEvent->lists($map, $listRow, true);

        $fieldMap =  array( 'id', 'title', 'thumb', 'pre_uri', 'uri', 'time', 'detail', 
                    'create_time', 'game_id', 'game', 'uid', 'user', 'statis', 'tags', 
                    'action', 'icons', 'type'
                    );
        $videos = $this->lists_format($vids, $fieldMap);
        if($videos){
            $count = count($videos);
            $this->timestamp = $videos[$count-1]['timestamp'];
        }

        $this->assign('data', $videos);
        $this->assign('topicTitle', $game['name']);

        if(IS_AJAX){

            $content = $this->fetch('Template/video');

            $this->ajaxReturn(array('state'=>0, 'info'=>'操作成功', 
                'data'=>array('content'=>$content,'total'=>count($videos), 'limit'=>$listRow)));
        }else{
             $this->display();
        }
       
    }

    private function _format_races($ids = [], $groupByDate = true) {
        $data = [];
        if(empty($ids)) return $data;
        $fieldMap = ['id', 'title', 'subtitle', 'race_date', 'race_hour', 'score', 'team', 'game', 'match', 'cover'];
        $rgEvent = event('RaceGroup');
        $vEvent = event('Video');
        foreach ($ids as $key => $value) {
            $detail = $rgEvent->info($value['id']);
            $detail['score'] = $detail['score']?array_map('intval', explode('-', $detail['score'])):[];
            $detail['game'] = $this->field_filter($detail['game'], ['id','name','logo']);
            $detail['match'] = $this->field_filter($detail['match'], ['id','title','cover', 'pc_cover']);
            $races = $vEvent->lists(['group_id' => $detail['id'], 'type' => 1], 0, true);
            if (!empty($races) && is_array($races)) {
                sort($races);
                $races = array_slice($races, 0, 4);
            }
            $detail = $this->field_filter($detail, $fieldMap);
            $detail['races'] = $races;
            $race[$detail['race_date']][] = $detail;
        }

        foreach ($race as $key => $value) {
            foreach ($value as $k => &$v) {
                uri_format($v['cover']);
                uri_format($v['match']['cover']);
                uri_format($v['match']['pc_cover']);
                if (empty($v['match']['pc_cover'])) {
                    $v['match']['pc_cover'] = $v['match']['cover'];
                }
            }
            if ($groupByDate) {
                $data[] = ['date'=>$key, 'list'=>$value];
            } else {
                $data = array_merge($data, $value);
            }
        }
        return $data;
    }

    /** 
     * 订阅游戏
     * @author Legend. <xcx_legender@qq.com>
     * @param $game_id 
     * @return 
     */
    
    public function scribe()
    {
        if (!UID) {
            $this->ajaxReturn(['status'=>0, 'info'=>'未登录']);
        }
        $game_id = I('id', 0, 'intval');
        if (!$game_id) {
            $this->error('游戏信息错误');
        }
        $game = event('Game')->info($game_id);
        if (empty($game)) {
            $this->error('游戏信息错误');
        }

        $res = event('GameScribe')->scribe(UID, $game_id);
        $res ? $this->ajaxReturn(['state'=>0, 'info'=>'操作成功']) : $this->ajaxReturn(['state'=>-1, 'info'=>'已经订阅']);
    }
    /** 
     * 取消订阅
     * @author Legend. <xcx_legender@qq.com>
     * @param 
     * @return 
     */
    public function unscribe()
    {
        if (!UID) {
            $this->ajaxReturn(['status'=>0, 'info'=>'未登录']);
        }
        $game_id = I('id', 0, 'intval');
        if (!$game_id) {
            $this->error('游戏信息错误');
        }
        $game = event('Game')->info($game_id);
        if (empty($game)) {
            $this->error('游戏信息错误');
        }
        $res = event('GameScribe')->unscribe(UID, $game_id);
        $res ? $this->ajaxReturn(['state'=>0, 'info'=>'取消成功']) : $this->ajaxReturn(['state'=>-1, 'info'=>'未订阅不能取消']);
    }
}